import subprocess
import os
import click
from typing import Dict

class LocalLkpBackend:
    def run(self, job_config_path: str, runs: int = 3) -> str:
        """
        在本地执行一个LKP任务 N 次 (install 一次, run N 次)。
        返回LKP结果目录的路径。
        """
        lkp_src = os.environ.get('LKP_SRC')
        if not lkp_src:
            raise RuntimeError("环境变量 LKP_SRC 未设置，请先设置 LKP_SRC。")
        lkp_bin = os.path.join(lkp_src, 'bin', 'lkp')

        install_cmd = ['sudo', lkp_bin, 'install', job_config_path]
        click.secho(f"     执行安装命令: {' '.join(install_cmd)}", fg='yellow')
        self._execute_command(install_cmd)
        
        # 步骤 2: 循环执行 'run' 命令 N 次
        for i in range(1, runs + 1):
            run_cmd = ['sudo', lkp_bin, 'run', job_config_path]
            click.secho(f"     开始第 {i}/{runs} 次运行: {' '.join(run_cmd)}", fg='yellow')
            self._execute_command(run_cmd)

        # 步骤 3: 获取结果路径
        # TODO: 需要一个可靠的方法来从LKP或其配置文件中确定最终的结果目录路径。
        # 暂时返回一个占位符路径，实际实现需要替换。
        result_root_path = f"/path/to/lkp/results/{os.path.basename(job_config_path).replace('.yaml', '')}"
        click.secho(f"     {runs}次运行全部完成。结果聚合于: {result_root_path}", fg='green')
        return result_root_path

    def _execute_command(self, cmd: list):
        """辅助函数，用于执行命令并实时打印输出。"""
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding='utf-8')
        while True:
            output = process.stdout.readline()
            if output == '' and process.poll() is not None:
                break
            if output:
                click.secho(f"       | {output.strip()}", fg='white')
        
        if process.returncode != 0:
            raise RuntimeError(f"命令 '{' '.join(cmd)}' 执行失败，返回码: {process.returncode}")
